package com.example.controller;

import com.example.constant.Constants;
import com.example.model.Result;
import com.example.model.UserInfo;
import com.example.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 阿宾
 * Date: 2025-04-10
 * Time: 20:21
 */
@RequestMapping("/user")
@RestController
public class UserController {

    @Autowired
    private UserService userService;
    /**
     * 登录接口实现
     * @param userInfo 用户对象
     * @return true或false
     */
    @RequestMapping(value = "/login",produces = "application/json")
    public Result login(UserInfo userInfo, HttpSession session){
        //1.参数校验
        if(!StringUtils.hasLength(userInfo.getUserName())||
        !StringUtils.hasLength(userInfo.getPassword())){
            return Result.fail("用户名或密码为空");
        }
        //2.验证用户名和密码是否正确，与数据库对比
        //2.1 接收到逻辑层返回的数据库信息
        UserInfo userInfoFromMysql = userService.selectUserByName(userInfo.getUserName());
        //2.2 先判断数据库是否存在信息
        if(userInfoFromMysql == null){
            return Result.fail("用户不存在");
        }
        //2.3 判断用户存在，校验密码是否正确
        if(!userInfo.getPassword().equals(userInfoFromMysql.getPassword())){
            return Result.fail("密码错误");
        }
        //3.校验密码相等
        //返回响应结果，使用session存储数据
        session.setAttribute(Constants.USER_SESSION_KEY,userInfoFromMysql);
        return Result.success(true);
    }
}
